import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import PropTypes from 'prop-types'
import { View, ScrollView, Image } from '@tarojs/components'
import { AtToast } from "taro-ui"
import classNames from 'classnames'
import _findIndex from 'lodash/findIndex'
// import ImgLoader from '@/components/ImgLoader'
import { delayQuerySelector, uuid } from '@/utils'
import './index.scss'
const ENV = Taro.getEnv()
const listId = `list-${uuid()}`

type Props = {
    list: Array<any>
    activeMenuItemId: string | number | null
    isVibrate: boolean
    isShowToast: boolean
    onClick: Function
}
type State = {
    _scrollIntoView: string
    _tipText: string
    _isShowToast: boolean
    currentIndex: number
}
class IndexNew extends Component<Props, State> {
    protected windowH: number
    protected keyHeight: number
    protected viewVisiableH: number
    protected listId: number
    protected currentIndex: number
    protected timeoutTimer: any
    static defaultProps = {
        list: [],
        activeMenuItemId: null,
        isShowToast: true,
        isVibrate: true,
        onClick: () => { }
    }
    static propTypes = {}
    constructor() {
        super(...arguments)
        this.state = {
            _scrollIntoView: '',
            //   _scrollTop: 0,
            _tipText: '',
            _isShowToast: false,
            currentIndex: 0
        }
        this.windowH = 0
        this.keyHeight = 0
        this.viewVisiableH = 0
        this.currentIndex = -1
        this.timeoutTimer = null
    }

    handleClick = (...arg) => this.props.onClick(...arg)

    catchTouchMove = event => {
        event.stopPropagation()
        event.preventDefault()
    }

		handleLetter=(item)=>{
			console.log('item',item)
			this.setState({
				_scrollIntoView:item
			})
		}


    handleKeysClick(idx, key) {
        this.currentIndex = idx
        this.updateState({
            _scrollIntoView: key,
            _tipText: key
        })
    }

    handleTouchMove = event => {
        event.stopPropagation()
        event.preventDefault()
        const { list } = this.props
        const offsetTop = (this.viewVisiableH / 2 - ( this.keyHeight * list.length) / 2) + (this.windowH - this.viewVisiableH)
        const pageY = event.touches[0].pageY
        let index = Math.floor(( pageY - offsetTop) / this.keyHeight)

        if (index >= 0
            && index <= list.length
            &&  this.currentIndex !== index
        ) {
            index = index === list.length ? index - 1 : index
            this.currentIndex = index

            this.jumpTarget(index)
        }
    }

    handleTouchEnd = () => {
        this.currentIndex = -1
    }

    jumpTarget(idx) {
        const { list } = this.props
        let _scrollIntoView = list[idx].key

        this.updateState({
            _scrollIntoView,
            _tipText: _scrollIntoView
        })
    }

    __jumpTarget(key) {
        const { list } = this.props
        const index = _findIndex(list, ['key', key])
    }

    updateState(state) {
        const { isShowToast, isVibrate } = this.props
        const { _scrollIntoView, _tipText } = state

        this.setState({
            _scrollIntoView,
            _tipText,
            _isShowToast: isShowToast
        }, () => {
            clearTimeout(this.timeoutTimer)
            this.timeoutTimer = setTimeout(() => {
                this.setState({
                    _tipText: '',
                    _isShowToast: false
                })
            }, 1000)
        })

        if (isVibrate) {
            Taro.vibrateShort()
        }
    }

    initData() {
        delayQuerySelector(this, '.index-list-wrap', 0).then(rect => {
            if (rect[0]) {
                this.viewVisiableH = rect[0].height
            }
        })
        delayQuerySelector(this, '.key').then(rect => {
            if (rect[0]) {
                this.keyHeight = rect[0].height
            }

        })

    }

    UNSAFE_componentWillReceiveProps(nextProps) {
        if (nextProps.list.length !== this.props.list.length) {
            this.initData()
        }
    }

    componentDidMount() {
        this.initData()
    }

    UNSAFE_componentWillMount() {
        this.windowH = Taro.getSystemInfoSync().windowHeight
    }

    render() {
        const { list, activeMenuItemId } = this.props
        const { _scrollIntoView, _isShowToast, _tipText } = this.state

        let menus = list.map( (dataList, i) => {
            return <View key={String(i)} className="index-list-scroll">
                <View className='title'
                    key={dataList.key}
                    id={dataList.key}
                >
                    {dataList.title}
                </View>
                <View className='items-wrap'>
                    {dataList.items.map((item) =>

                        <View key={String(item.brandId)}
                            onClick={this.handleClick.bind(this, item)}
                            className={
                                classNames('item', {
                                    'active': parseInt(item.brandId) === Number(activeMenuItemId)
                                })
                            }>
                            {/* <ImgLoader width='76rpx' height='76rpx' iconSize='40' originalUrl={item.logo} lazyLoad={true} mode='aspectFit' /> */}
                            <Image lazyLoad={true} mode='aspectFit' src={item.logo}></Image>
                            <View className='text'>{item.name}</View>
                        </View>
                    )}
                </View>
            </View>
        })
        let indexesList = list.map( (indexList, i) => (
					// onClick={this.handleKeysClick.bind(this, i, indexList.key)}
            <View
                key={indexList.key}
                className='key'
								onClick={()=>this.handleLetter(indexList.key)}>
                {indexList.key}
            </View>
        ))
        return (
            <View className='index-list-wrap'
                onTouchMove={this.catchTouchMove}
            >
                <ScrollView
                    scrollY={true}
                    scroll-into-view={_scrollIntoView}
                    className='index-list'>
                    {menus}
                </ScrollView>
                <AtToast
                    isOpened={_isShowToast}
                    text={_tipText}
                    duration={1500}
                    hasMask={false}>
                </AtToast>
                <View className='key-wrap'>
                    {indexesList}
                </View>
            </View>
        )
    }
}

export default IndexNew
